package com.lxw.cmsClient.mq;

import com.lxw.cmsClient.dao.CmsPageDao;
import com.lxw.cmsClient.dao.CmsPreviewDao;
import com.lxw.framework.domain.cms.CmsPage;
import com.lxw.framework.domain.cms.response.CmsCode;
import com.lxw.framework.domain.filesystem.response.FileSystemCode;
import com.lxw.framework.exception.BizException;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Component;
import sun.rmi.runtime.Log;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Optional;

@Component
@RabbitListener(queues = "${yh.mq.queue}")
@Slf4j
public class PostPageMq {
    @Autowired
    CmsPageDao cmsPageDao;
    @Autowired
    CmsPreviewDao cmsPreviewDao;
    @Autowired
    GridFsTemplate gridFsTemplate;
    @Autowired
    GridFSBucket gridFSBucket;

    //监听消息对列，获取PageId
    @RabbitHandler
    public void process(String id) {
        log.info("监听对列" + id);
        //1获取id
        Optional<CmsPage> byId = cmsPageDao.findById(id);
        if (!byId.isPresent()) {
            throw new BizException(CmsCode.CMS_FANDBYID_PAGEISNULL);
        }
        CmsPage cmsPage = byId.get();
        //2 读文件
        //静态文件Id htmlFileId
        String htmlFileId = cmsPage.getHtmlFileId();
        //通过id在GridFS存储桶中查询出gf文件
        Criteria criteria = Criteria.where("_id").is(htmlFileId);
        GridFSFile one = gridFsTemplate.findOne(Query.query(criteria));

        //3 获取文件流
        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(one.getObjectId());
        // 将GridFSFile文件 加载在流上
        GridFsResource gridFsResource = new GridFsResource(one, gridFSDownloadStream);
        // 4 将文件写入磁盘 位置:物理路径+访问地址+页面名称
        String fileName = cmsPage.getPagePhysicalPath() + cmsPage.getPageWebPath() + cmsPage.getPageName();
        try {
            IOUtils.copy(gridFsResource.getInputStream(), new FileOutputStream(fileName));
        } catch (IOException e) {
            e.printStackTrace();
            throw new BizException(FileSystemCode.FS_UPLOADFILE_FILEISNULL);
        }
    }
}
